package com.example.lib_common.base

import android.content.Context
import android.hardware.input.InputManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.R
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.state.UIState
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2025/1/14
 */
abstract class BaseActivity<VM:BaseViewModel,VDB:ViewDataBinding>:AppCompatActivity() {
    companion object{
        private const val TAG = "BaseActivity"
    }
    protected lateinit var mBinding: VDB//数据绑定view
    abstract val mLayoutResId:Int //布局id
    abstract val mViewModel:VM //viewmodel
    protected lateinit var mRootView:ViewGroup //根布局  window-->decorView-->contentView(xml布局)
    protected  var mLoadingView: View?= null //加载中布局


    open val mPageCanBack:Boolean = true //是否可返回
    private var lastPressBack = 0L //上一次点击返回的时间戳


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //ARouter依赖注入
        ARouter.getInstance().inject(this)
        //绑定布局
        mBinding = DataBindingUtil.setContentView(this,mLayoutResId)
        mBinding.lifecycleOwner = this //生命周期感知
        //初始化全局加载中UI
        initGlobalView()
        //初始化
        initView()
        initStatusBar()
        initListener()
        initData()

    }

    private fun initGlobalView() {
        mRootView = window.decorView as ViewGroup
        initLoadingView()
    }
    private fun initLoadingView(){
        if(mLoadingView == null){
            mLoadingView = layoutInflater.inflate(R.layout.dialog_common_progress,mRootView,false)
            setLoadingViewVisible(false)
            mRootView.addView(mLoadingView)
        }
    }

    /**
     * 显示隐藏加载中
     */
    fun setLoadingViewVisible(show:Boolean,msg:String = ""){

        mLoadingView?.apply { //apply标准库函数 节省变量
            val textView = findViewById<TextView>(R.id.tv_text)
            if(show && msg.isNotEmpty()){
                textView.text = msg
            }
            if(show) visibility = View.VISIBLE else visibility = View.GONE
        }
    }

    /**
     * 通用状态监听：Loading显示和隐藏、错误提示
     */
    open fun addCommonStateListener(state:StateFlow<UIState>){
        state.observeWithLifecycle(this){
            when(it){
                is UIState.Loading -> {
                    setLoadingViewVisible(true)
                }
                is UIState.Error -> {
                    setLoadingViewVisible(false)
                    Toast.makeText(this@BaseActivity,it.message,Toast.LENGTH_SHORT)
                }
                is UIState.Success -> {
                    setLoadingViewVisible(false)
                }
                else -> {
                }
            }
        }
    }


    abstract fun initView()
    abstract fun initData()
    abstract fun initListener()
    fun initStatusBar(){
        ImmersionBar.with(this).init()
    }
    /**
     * 隐藏键盘
     */
    fun hideKeyBroad(view:View){
        val inputManager = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(view.windowToken,0)
    }
    /**
     * 显示键盘
     */
    fun showKeyBroad(view:View){
        view.requestFocus() //获得焦点
        val inputManager = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT)
    }

    /**
     * 点击返回处理
     * 1.当前activity是否可返回（A--》B B可返回的 A不可返回）
     *  可返回：默认返回
     *  不可返回：
     *      2.当前activity有无fragment
     *          无：退出app
     *          有：判断fragment是否可返回
     *              可返回：默认返回
     *              不可返回：退出app
     */
    override fun onBackPressed() {
        val timeStamp = System.currentTimeMillis()
        //1.当前activity是否可返回
        if(mPageCanBack){
            Log.d(TAG, "返回上一个activity: ")
            super.onBackPressed()
            return
        }
        //2.当前activity有无fragment
        val fragments = supportFragmentManager.fragments.filterIsInstance<BaseFragment<*,*>>()
        //无fragment：退出app
        if(fragments.isEmpty() && isPressBackToExitApp(timeStamp)){
            Log.d(TAG, "此activity无fragment，关闭app: ")
            super.onBackPressed()
            return
        }
        //有fragment
        for (fragment in fragments){
            if(fragment.isVisible){
                //可返回
                if(fragment.mCanBack){
                    super.onBackPressed()
                    return
                }
                //不可返回:退出app
                if(isPressBackToExitApp(timeStamp)){
                    super.onBackPressed()
                    return
                }
            }
        }

    }

    /**
     * 退出app
     */
    private fun isPressBackToExitApp(timeStamp:Long):Boolean{
        if(lastPressBack == timeStamp){
            return false
        }
        if(timeStamp - lastPressBack < 2000){
            return true
        }else{
            Toast.makeText(this,"再按一次退出",Toast.LENGTH_SHORT).show()
            lastPressBack = timeStamp
            return false
        }

    }
}